<template>
  <el-dialog
    :title="state.type === 'add' ? '添加模块' : '修改模块'"
    v-model="state.visible"
    width="400px"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="模块名称" prop="name">
        <el-input type="text" v-model="state.ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="模块描述" prop="desc">
        <el-input type="text" v-model="state.ruleForm.desc"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <el-input type="text" v-model="state.ruleForm.tag"></el-input>
      </el-form-item>
      <el-form-item required label="封面图片" prop="coverPicture">
        <el-upload class="avatar-uploader"
                   :action="state.uploadImgServer" accept="jpg,jpeg,png"
                   :headers="{token: state.token}"
                   :show-file-list="false"
                   :before-upload="handleBeforeUpload"
                   :on-success="handleUrlSuccess">
          <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.ruleForm.coverPicture" :src="state.ruleForm.coverPicture" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref , getCurrentInstance} from 'vue'
import { useRoute } from 'vue-router'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import {localGet, uploadImgServer} from "@/utils";

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})
const { proxy } = getCurrentInstance()
const formRef = ref(null)
const route = useRoute()
const state = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  type: 'add',
  visible: false,
  moduleCode: 0,
  ruleForm: {
    name: '',
    desc: '',
    tag: '',
    coverPicture: '',
  },
  rules: {
    name: [
      { required: 'true', message: '名称不能为空', trigger: ['change'] }
    ]
  },
})

const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
const handleUrlSuccess = (val) => {
  state.ruleForm.coverPicture = proxy.$filters.prefix(val.data.url) || ''
}
// 获取详情
const getDetail = (id) => {
  axios.post(`api/admin/module/v1/detail`,{
    moduleCode: id
  }).then(res => {
    state.ruleForm = {
      name: res.moduleName,
      desc: res.moduleDesc,
      tag: res.tag,
      coverPicture: res.coverPicture
    }
    state.moduleCode = id;
  })
}
// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    state.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
    const { level = 1, parent_id = 0 } = route.query
    state.ruleForm = {
      name: '',
      rank: ''
    }
    state.parentId = parent_id
    state.categoryLevel = level
  }
}
// 关闭弹窗
const close = () => {
  state.visible = false
}
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      let params = {
        moduleName: state.ruleForm.name,
        moduleDesc: state.ruleForm.desc,
        coverPicture: state.ruleForm.coverPicture,
        tag: state.ruleForm.tag
      };
      let url = 'api/admin/module/v1/create';
      let message = '添加成功';
      if (props.type != 'add') {
        url = 'api/admin/module/v1/update';
        message = '修改成功';
        params.moduleCode = state.moduleCode;
      }
      axios.post(url, params).then(() => {
        ElMessage.success('添加成功')
        state.visible = false
        // 接口回调之后，运行重新获取列表方法 reload
        if (props.reload) props.reload()
      })
    }
  })
}
defineExpose({ open, close })
</script>
<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>
